from multiprocessing import Pool

import requests
import re
import os


def get_ts_ls(d):
    mu = d['m3u8Url']
    chapter = d['chapter']
    name = d['name']
    filepath = "{}-{}".format(chapter, name)
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    txt = requests.get(mu).content.decode('utf-8')
    ts_r = re.compile(r"\d+_\w+_\w+\.ts")
    uri_r = re.compile(r"http://mooc2vod.stu.126.net/nos/hls/\d+/\d+/\d+/")
    uri = uri_r.search(mu).group()
    ts_ls = [uri + t for t in ts_r.findall(txt)]
    return ts_ls,filepath

def normal_download(ts_ls, filepath):
    for u in ts_ls:
        with open(filepath + "/" + u[-10:], 'wb') as fp:
            fp.write(requests.get(u).content)

def download_m3u8(m3u8_url):
    ts_ls, filepath = get_ts_ls(m3u8_url)
    normal_download(ts_ls, filepath)

if __name__ == "__main__":
    import time
    with open('term.txt', 'r', encoding='utf-8') as fp:
        ls = eval(fp.read())
    start = time.perf_counter()
    pool = Pool(4)
    pool.map(download_m3u8, ls)
    end = time.perf_counter()
    print(end - start)